﻿using System;
using System.IO;

namespace SharpTag.ID3
{
    /// <summary>
    /// Concrete implementation of the <see cref="ITagReader"/> interface.
    /// </summary>
    public class ID3V1TagReader : ITagReader
    {
        private const int ID3V1TagLength = 128;
        private const int ID3IdLength = 3;
        private BinaryReader br;

        /// <summary>
        /// Reads the ID3v1 tag information from a file.
        /// </summary>
        /// <param name="taggedFile">The <see cref="IFile"/> object.</param>
        /// <returns>A byte array containg the ID3v1 tag information.</returns>
        public byte[] ReadTagBytes(IFile taggedFile)
        {
            var returnBytes = new byte[ID3V1TagLength];
            br = new BinaryReader(File.Open(taggedFile.Path, FileMode.Open, FileAccess.Read, FileShare.None));
            br.BaseStream.Seek(-ID3V1TagLength, SeekOrigin.End);
            br.Read(returnBytes, 0, ID3V1TagLength);
            br.Close();
            var idChar = new char[ID3IdLength];
            Array.Copy(returnBytes, 0, idChar, 0, ID3IdLength);

            var idString = new string(idChar);

            return idString == "TAG" ? returnBytes : null;
        }

    }
}
